"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountReqHandler = void 0;
const ErrorCode_1 = require("../src/config/ErrorCode");
const GameConfig_1 = require("../src/config/GameConfig");
const ServerConfig_1 = require("../src/config/ServerConfig");
const DateUtil_1 = require("../src/engine/utils/DateUtil");
const IdentifiUtil_1 = require("../src/engine/utils/IdentifiUtil");
const Logger_1 = require("../src/engine/utils/Logger");
const Md5Helper_1 = require("../src/engine/utils/Md5Helper");
const WebUtil_1 = require("../src/engine/utils/WebUtil");
const ResponseModel_1 = require("../src/model/ResponseModel");
const AccountDao_1 = require("./dao/AccountDao");
const UserDao_1 = require("./dao/UserDao");
const AccountEntity_1 = require("./entity/AccountEntity");
const WechatSdkManager_1 = require("./WechatSdkManager");
const request = require('request');
const crypto = require("crypto");
const routerMap = {
    updateServerStatus: "/updateServerStatus",
    register: "/register",
    account_auth: "/account_auth",
    wechat_auth: "/wechat_auth",
    get_user_data: "/get_user_data"
};
class AccountReqHandler {
    init(app) {
        for (const key in routerMap) {
            app.use(routerMap[key], this.onBaseRoot.bind(this));
        }
    }
    onBaseRoot(req, resp) {
        try {
            let ip = WebUtil_1.WebUtil.getIpByExpressReq(req);
            Logger_1.Logger.log("onBaseRoot==", ip, req.baseUrl);
            if (req.baseUrl == routerMap.updateServerStatus) {
                ServerConfig_1.ServerConfig.initConfig(ServerConfig_1.ServerConfig.nowServerConfig.nowPort);
                resp.end("success");
            }
            else if (req.baseUrl == routerMap.register) {
                this.checkBody(ip, req, resp, this.on_register.bind(this));
            }
            else if (req.baseUrl == routerMap.account_auth) {
                this.checkBody(ip, req, resp, this.on_account_auth.bind(this));
            }
            else if (req.baseUrl == routerMap.wechat_auth) {
                this.checkBody(ip, req, resp, this.on_wechat_auth.bind(this));
            }
            else if (req.baseUrl == routerMap.get_user_data) {
                this.checkBody(ip, req, resp, this.on_get_user_data.bind(this));
            }
        }
        catch (error) {
            Logger_1.Logger.warn("onBaseRoot error", error);
        }
    }
    checkBody(ip, req, resp, callback) {
        if (req.body) {
            try {
                let jsonObj = JSON.parse(req.body);
                let k = jsonObj["k"];
                let data = jsonObj["data"];
                if (k == Md5Helper_1.Md5Helper.getMd5_encrypt(JSON.stringify(data))) {
                    callback && callback(req, resp, data, ip);
                }
                else {
                    Logger_1.Logger.error("收到非法Http请求 key", ip, req.body);
                    resp.end();
                }
            }
            catch (error) {
                Logger_1.Logger.error("收到非法Http请求body", ip, req.body, error);
                resp.end();
            }
        }
        else {
            resp.end();
        }
    }
    on_register(req, resp, data, ip) {
        return __awaiter(this, void 0, void 0, function* () {
            Logger_1.Logger.log("on_register=", data, ip);
            let account = data["account"];
            let password = data["password"];
            let channel = data["channel"];
            let os = data["os"];
            let phone_type = data["phone_type"];
            let bundle_name = data["bundle_name"];
            let system_version = data["system_version"];
            let udid = data["udid"];
            if (!IdentifiUtil_1.IdentifiUtil.isEmojiCharacter(account)) {
                let oldAccount = yield AccountDao_1.AccountDao.get_account_info(account);
                // Logger.log("on_register===isExist=", isExist)
                if (oldAccount) {
                    resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "已存在账号")));
                }
                else {
                    // let isExistIp: boolean = await AccountDao.is_ip_exist(ip)
                    let token = Md5Helper_1.Md5Helper.createToken(account);
                    let accountEntity = new AccountEntity_1.AccountEntity();
                    accountEntity.account = account;
                    accountEntity.password = password;
                    accountEntity.account_type = GameConfig_1.GameConfig.Account_Type.Account;
                    accountEntity.token = token;
                    accountEntity.status = GameConfig_1.GameConfig.Status_Type.Normal;
                    accountEntity.ip = ip;
                    accountEntity.nick_name = account;
                    accountEntity.channel = channel;
                    accountEntity.os = os;
                    accountEntity.phone_type = phone_type;
                    accountEntity.bundle_name = bundle_name;
                    accountEntity.system_version = system_version;
                    accountEntity.udid = udid;
                    accountEntity.sex = GameConfig_1.GameConfig.Sex_Type.Mail;
                    accountEntity.create_time = DateUtil_1.default.formatDateStr(DateUtil_1.default.now());
                    accountEntity = yield AccountDao_1.AccountDao.update_account(accountEntity);
                    if (accountEntity) {
                        let data = {
                            "account": account,
                            "token": token,
                            "nickname": account,
                            "sex": accountEntity.sex,
                            "headimgurl": accountEntity.headimgurl,
                            "account_type": accountEntity.account_type,
                            "server": yield this.getHallServer(account)
                        };
                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Suc, "", data)));
                    }
                    else {
                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "数据库错误，创建账号失败")));
                    }
                }
            }
            else {
                resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "账号包含非法字符")));
            }
        });
    }
    on_account_auth(req, resp, data, ip) {
        return __awaiter(this, void 0, void 0, function* () {
            // Logger.log("on_account_auth=", data, ip)
            let account = data["account"];
            let password = data["password"];
            let channel = data["channel"];
            let os = data["os"];
            let phone_type = data["phone_type"];
            let bundle_name = data["bundle_name"];
            let system_version = data["system_version"];
            let udid = data["udid"];
            let accountResult = yield AccountDao_1.AccountDao.get_account_info(account);
            if (accountResult) {
                if (password == accountResult.password) {
                    if (accountResult.status == GameConfig_1.GameConfig.Status_Type.FengJin) {
                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "用户被冻结")));
                    }
                    else {
                        let token = Md5Helper_1.Md5Helper.createToken(account);
                        accountResult.ip = ip;
                        accountResult.channel = channel;
                        accountResult.os = os;
                        accountResult.phone_type = phone_type;
                        accountResult.bundle_name = bundle_name;
                        accountResult.system_version = system_version;
                        accountResult.udid = udid;
                        accountResult.token = token;
                        accountResult.last_login_time = DateUtil_1.default.formatDateStr(DateUtil_1.default.now());
                        accountResult = yield AccountDao_1.AccountDao.update_account(accountResult);
                        if (accountResult) {
                            let respData = {
                                "account": account,
                                "token": token,
                                "nickname": accountResult.nick_name,
                                "sex": accountResult.sex,
                                "headimgurl": accountResult.headimgurl,
                                "account_type": GameConfig_1.GameConfig.Account_Type.Account,
                                "server": yield this.getHallServer(account)
                            };
                            resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Suc, "", respData)));
                        }
                        else {
                            resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Db_Error, "数据库错误")));
                        }
                    }
                }
                else {
                    Logger_1.Logger.log("on_account_auth账号密码不对", password, accountResult["password"]);
                    resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.LoginError_NoPass, "登录密码错误")));
                }
            }
            else {
                resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.LoginError_NoUser, "不存在该用户")));
            }
        });
    }
    on_wechat_auth(req, resp, data, ip) {
        return __awaiter(this, void 0, void 0, function* () {
            Logger_1.Logger.log("on_wechat_auth=", data, ip);
            let code = data["code"];
            let channel = data["channel"];
            let os = data["os"];
            let phone_type = data["phone_type"];
            let bundle_name = data["bundle_name"];
            let system_version = data["system_version"];
            let udid = data["udid"];
            WechatSdkManager_1.WechatSdkManager.instance.get_access_token(code, (respData) => {
                if (respData.status == 200) {
                    Logger_1.Logger.log("get_access_token===resp=", respData.data);
                    if (respData.data["errcode"] && respData.data["errmsg"]) {
                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, respData.data["errmsg"])));
                    }
                    else {
                        let openid = respData.data["openid"];
                        let access_token = respData.data["access_token"];
                        WechatSdkManager_1.WechatSdkManager.instance.get_userinfo(access_token, openid, (respData) => __awaiter(this, void 0, void 0, function* () {
                            if (respData.status == 200) {
                                Logger_1.Logger.log("get_userinfo===resp=", respData.data);
                                if (respData.data["errcode"] && respData.data["errmsg"]) {
                                    resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, respData.data["errmsg"])));
                                }
                                else {
                                    // let unionid: string = respData.data["openid"]
                                    let unionid = respData.data["unionid"];
                                    let openid = respData.data["openid"];
                                    let nickname = respData.data["nickname"];
                                    let sex = respData.data["sex"];
                                    let headimgurl = respData.data["headimgurl"];
                                    let token = Md5Helper_1.Md5Helper.createToken(unionid);
                                    let accountEntity = yield AccountDao_1.AccountDao.get_account_info(unionid);
                                    if (accountEntity) {
                                    }
                                    else {
                                        accountEntity = new AccountEntity_1.AccountEntity();
                                        accountEntity.password = "123456";
                                        accountEntity.account_type = GameConfig_1.GameConfig.Account_Type.Wechat;
                                    }
                                    accountEntity.sex = sex;
                                    accountEntity.nick_name = nickname;
                                    accountEntity.headimgurl = headimgurl;
                                    accountEntity.token = token;
                                    accountEntity.ip = ip;
                                    accountEntity.channel = channel;
                                    accountEntity.os = os;
                                    accountEntity.phone_type = phone_type;
                                    accountEntity.bundle_name = bundle_name;
                                    accountEntity.system_version = system_version;
                                    accountEntity.udid = udid;
                                    accountEntity = yield AccountDao_1.AccountDao.update_account(accountEntity);
                                    if (accountEntity) {
                                        let data = {
                                            "account": accountEntity.account,
                                            "token": accountEntity.token,
                                            "nickname": accountEntity.nick_name,
                                            "sex": accountEntity.sex,
                                            "headimgurl": accountEntity.headimgurl,
                                            "account_type": accountEntity.account_type,
                                        };
                                        data["server"] = yield this.getHallServer(unionid);
                                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Suc, "", data)));
                                    }
                                    else {
                                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Db_Error, "数据库错误,创建账号失败")));
                                    }
                                }
                            }
                            else {
                                resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, respData.statusText)));
                            }
                        }));
                    }
                }
                else {
                    Logger_1.Logger.log("get_access_token===resp==error=", respData.statusText);
                    resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, respData.statusText)));
                }
            });
        });
    }
    getHallServer(account) {
        return __awaiter(this, void 0, void 0, function* () {
            // let resultServerConfig: ServerConfig = await ServerManager.instance.is_in_server(account)
            // if (!resultServerConfig) {
            // resultServerConfig = ServerConfig.randomHallServer()
            // }
            // return resultServerConfig;
            return ServerConfig_1.ServerConfig.randomHallServer();
        });
    }
    on_get_user_data(req, resp, data, ip) {
        return __awaiter(this, void 0, void 0, function* () {
            let userid = data["userid"];
            let userData = yield UserDao_1.UserDao.get_user_data_by_userid(userid);
            resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Suc, "", userData)));
        });
    }
}
exports.AccountReqHandler = AccountReqHandler;
AccountReqHandler.instance = new AccountReqHandler();
